package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询缓存内的商户列表
     *
     * @return
     */
    @Override
    public List<ShopType> queryTypeList() {

        // TODO

        //1.查询redis中的缓存列表
//        ArrayList<ShopType> shopTypeList = new ArrayList<>();
//        String jsonStr = null;
//        1.2 获取redis中所有值
//        while ((jsonStr = stringRedisTemplate.opsForList().leftPop(CACHE_SHOP_TYPE_KEY)) != null) {
//            //遍历获取到List中每一个对象
//            ShopType shopType = JSONUtil.toBean(jsonStr, ShopType.class);
//            shopTypeList.add(shopType);
//        }
        String shopTypeJsonStr = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY);

//        List<ShopType> shopTypeList = RedisTemplate.opsForList().range(CACHE_SHOP_TYPE_KEY, 0, -1);

        //2.缓存存在则返回列表
//        if (!CollectionUtils.isEmpty(shopTypeList)) {
//            return shopTypeList;
//        }

        if (StrUtil.isNotBlank(shopTypeJsonStr)) {
            JSONArray jsonArray = JSONUtil.parseArray(shopTypeJsonStr);
            List<ShopType> typeList = JSONUtil.toList(jsonArray, ShopType.class);
            return typeList;
        }

        //3.缓存不存在则查询数据库
        List<ShopType> shopTypeListDB = query().list();

        //4.数据库中不存在则返回未找到
        if (CollectionUtils.isEmpty(shopTypeListDB)) {
            return null;
        }

        //5.数据库中存在，先存入redis
//        for (ShopType shopType : shopTypeListDB) {
//            String jsonStr1 = JSONUtil.toJsonStr(shopType);
//            stringRedisTemplate.opsForList().rightPush(CACHE_SHOP_TYPE_KEY, jsonStr1);
//        }

        // 5.1 将list集合转为JsonStr
        String toJsonStr = JSONUtil.toJsonStr(shopTypeListDB);
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY, toJsonStr);

        //6.返回数据
        return shopTypeListDB;
    }
}
